<template>
  <!-- 安全责任指标考核总工作项维护 -->
  <base-breadcrumb>
    <div class="page-body page-height">
      <a-card :bordered="false" class="body-left">
        <title-name title="岗位列表" />
        <div class="tree-container page-height-tree">
          <JobsTree :filterJobFn="handleFilterJob" :selectedKeys.sync="jobSelectedKeys" @select="handleTreeNodeSelect" />
        </div>
      </a-card>
      <a-card class="body-right">
        <!-- <title-name title="安全责任考核项" /> -->
        <div class="table-operateors mb20">
          <a-button type="primary" @click="handleUpdate('add')" v-btnPermission="'hse_016_add_01'">添加项</a-button>
        </div>
        <s-table
          ref="table"
          size="default"
          rowKey="id"
          :columns="columns"
          :data="loadData"
          :alert="true"
          show-size-changer
          show-quick-jumper
          :showPagination="false"
        >
          <template slot="serial" slot-scope="text, record, index">{{ index + 1 }}</template>
          <template slot="operator" slot-scope="text, record">
            <a class="base-btn" @click="handleUpdate('edit', record)" v-btnPermission="'hse_016_edi_02'">编辑</a>
          </template>
        </s-table>
      </a-card>
    </div>
    <update-total
      :init-data="childInitData"
      :form-data="formList"
      :default-data="defaultFormData"
      :fullRowTypes="['TEXT_AREA']"
      :getColumnCode="getColumnCode"
      v-if="visible.update"
      @cancel="visible.update = false"
      @confirm="handleUpdateTotalConfirm"
    />
  </base-breadcrumb>
</template>

<script>
import JobsTree from '@/components/JobsTree'
import {
  getExamHeadersByOrganization,
  getExamContentByOrganization,
  addExamHeaders,
} from '@/api/safetySupervision/common.js'
import UpdateTotal from './UpdateTotal.vue'
import { STable } from '@/components'

const columns = [
  {
    title: '考核项目',
    dataIndex: 'examItem',
  },
]
export default {
    name:'a'+Date.now(),  components: {
    STable,
    UpdateTotal,
    JobsTree,
  },
  data() {
    return {
      jobSelectedKeys: [],
      defaultFormData: {},
      curFormId: '',
      formList: [],
      childInitData: {},
      curPostId: '',
      curPostName: '',
      tableList: [],
      visible: {
        update: false,
      },
      columns: columns,
      queryParam: {},
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return new Promise((resolve, reject) => {
          resolve({
            data: this.tableList,
          })
        })
      },
    }
  },
  methods: {
    /**
     * 过滤掉不需要的岗位
     */
    handleFilterJob(list) {
      const blackList = ['安全总监', '项目经理']
      return list.filter(item => !blackList.includes(item.name))
    },
    getColumnCode(dataIndex) {
      const target = this.columns.find(item => item.dataIndex === dataIndex)
      return target && target.code || ''
    },
    async addExamHeaders() {
      const params = {
        postId: this.curPostId,
        assessmentForm: {
          formName: `${this.curPostName}安全责任考核表`,
          header: {
            items: [
              {
                code: 1,
                sort: 1,
                inputType: 'TEXT_AREA',
                name: '考核项目',
              },
              {
                code: 2,
                sort: 2,
                inputType: 'TEXT_AREA',
                name: '扣分标准22',
                width:"40%",
              },
              {
                code: 3,
                sort: 3,
                inputType: 'INPUT',
                name: '应得分',
              },
              {
                code: 4,
                sort: 4,
                inputType: 'SELECT',
                name: '状态',
              },
            ],
          },
        },
      }
      const [err, res] = await addExamHeaders(params)
      if (!err) {
        this.getHeaders(this.curPostId)
      }
    },
    handleUpdateTotalConfirm() {
      this.visible.update = false
      this.getContent(this.curPostId)
    },
    async getContent(id) {
      const [err, res] = await getExamContentByOrganization({ postId: id })
      if (!err) {
        this.tableList = res.data || []
        this.$refs.table.refresh(true)
      }
    },
    async getHeaders(id) {
      const [err, res] = await getExamHeadersByOrganization({ postId: id })
      if (!err) {
        const validateShouldScore = (rule, value, callback) => {
          const reg = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/
          if (reg.test(value) || !value) {
            callback()
          } else {
            callback(new Error('请输入正确的数字'))
          }
        }
        const columnList = res.data || []
        this.formList = [...res.data]
        this.formList.forEach((item) => {
          if (item.code === '4') {
            // 对应状态栏
            item.selectList = [
              {
                label: '可用',
                value: '可用',
              },
              {
                label: '不可用',
                value: '不可用',
              },
            ]
          }
          if (item.code === '3') {
            // 应得分表单项进行类型验证
            item.$attrs = {
              ...item.$attrs,
              rules: [
                {
                  required: true,
                  message: '请输入',
                  trigger: 'change'
                },
                {
                  validator: validateShouldScore,
                  trigger: 'blur',
                },
              ],
            }
          } else {
            item.$attrs = {
              ...item.$attrs,
              rules: [
                {
                  required: true,
                  message: item.inputType === 'INPUT' || item.inputType === 'TEXT_AREA' ? '请输入' : '请选择',
                  trigger: 'change'
                }
              ]
            }
          }
        })
        if (this.formList.length > 0) {
          this.curFormId = this.formList[0].formId
        }
        columnList.unshift({
          title: '序号',
          dataIndex: 'serial',
          scopedSlots: { customRender: 'serial' },
          width: 65,
        })
        columnList.push({
          title: ' 操作',
          dataIndex: 'operator',
          scopedSlots: { customRender: 'operator' },
          width: 100,
        })
        columnList.map((item)=>{
          if(item.title=='状态'){
            item.width = 100
          }
        })
        this.columns = columnList
      } else {
        if (err.data.message === '该岗位无考核表') {
          this.addExamHeaders()
        }
      }
    },
    handleTreeNodeSelect(keys, { selectedNodes, node }) {
      if (selectedNodes.length) {
        this.curPostName = selectedNodes[0].data.props.title
      } else {
        this.curPostName = ''
      }
      const selectedKeys = this.jobSelectedKeys
      if (selectedKeys.length) {
        this.curPostId = selectedKeys[0]
        this.getHeaders(this.curPostId)
        this.getContent(this.curPostId)
      } else {
        this.curPostId = ''
      }
    },
    handleUpdate(type, data = {}) {
      if (!this.curPostId) {
        this.$message.error('请先选择岗位')
        return
      }
      if (this.formList.length === 0) {
        this.$message.error('不存在可添加的考核项')
        return
      }
      this.childInitData = {
        pageType: type,
        ...data,
        formId: this.curFormId,
      }
      this.defaultFormData = { ...data }
      this.visible.update = true
    },
  },
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
.page-body {
  background-color: #fff;
  display: flex;
  .body-left {
    white-space: nowrap;
    width: 230px;
    // height: 75vh;
    @{deep}.ant-card-body {
      display: flex;
      flex-direction: column;
      height: 100%;
      scrollbar-width: none; /* Firefox */
      -ms-overflow-style: none; /* IE 10+ */
      ::-webkit-scrollbar {
        display: none; /* Chrome Safari */
      }
    }
    .tree-container {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .body-right {
    flex: auto;
    width: 400px;
    border-left: 1px solid rgba(231, 231, 231, 1);
  }
}
</style>